package org.aeon.fasttasks.core.recorder;

import org.aeon.fasttasks.core.util.CsvUtils;
import org.aeon.fasttasks.core.util.DateUtil;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author aeon
 * @createTime 2025/08/07  10:38
 * @description CSV记录器
 */
public class CsvRecorder extends AbstractCsvRecorder {

    private final static Logger log = LoggerFactory.getLogger(CsvRecorder.class);

    public CsvRecorder(String filePath, List<String> headers, boolean recordingTime) {
        super(filePath, headers, recordingTime);
    }

    @Override
    public void record(Object... contents) {
        try (CSVPrinter csvPrinter = CsvUtils.createCsvPrinter(path)) {
            handleHeader(csvPrinter);
            List<String> recordToWrite =
                    new ArrayList<>(Arrays.stream(contents).map(Object::toString).toList());
            if (recordingTime) {
                recordToWrite.add(DateUtil.formatTimestamp(Instant.now().toEpochMilli()));
            }
            // 写入批量内容
            CsvUtils.writeRecord(csvPrinter, recordToWrite);
        } catch (IOException e) {
            log.error("写入CSV批处理失败: {}", e.getMessage(), e);
        }
    }

}
